// 导出工具类
import md from './markdown'
import { logger } from './logger'

export class ExportUtils {
  // 导出为HTML
  static async exportToHTML(content: string, title: string = 'Markdown Document'): Promise<boolean> {
    try {
      logger.info('ExportUtils.exportToHTML called', { title })
      // 渲染Markdown为HTML
      const renderedContent = md.render(content)
      
      // 调用主进程导出HTML
      const result = await (window as any).electronAPI.exportHTML(renderedContent, title)
      logger.info('Export HTML result:', result)
      return !result.canceled
    } catch (error) {
      logger.error('导出HTML失败:', error)
      return false
    }
  }

  // 导出为PDF
  static async exportToPDF(content: string, title: string = 'Markdown Document'): Promise<boolean> {
    try {
      logger.info('ExportUtils.exportToPDF called', { title })
      // 渲染Markdown为HTML
      const renderedContent = md.render(content)

      // 优先使用主进程的PDF导出（Electron 环境）
      const api = (window as any).electronAPI
      if (api && typeof api.exportPDF === 'function') {
        const result = await api.exportPDF(renderedContent, title)
        logger.info('Export PDF (electron) result:', result)
        return !result.canceled
      }

      // Web 预览环境回退：使用 iframe 打印为 PDF
      const htmlContent = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>${title}</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1, h2, h3, h4, h5, h6 {
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: 600;
            line-height: 1.25;
        }
        pre {
            background-color: #f6f8fa;
            border-radius: 6px;
            padding: 16px;
            overflow: auto;
        }
        code {
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 85%;
        }
        blockquote {
            margin: 0;
            padding: 0 1em;
            color: #6a737d;
            border-left: 0.25em solid #dfe2e5;
        }
        @media print {
            body { padding: 0; }
        }
    </style>
</head>
<body>
    ${renderedContent}
</body>
</html>
      `

      const iframe = document.createElement('iframe')
      iframe.style.position = 'absolute'
      iframe.style.top = '-1000px'
      iframe.style.left = '-1000px'
      document.body.appendChild(iframe)

      const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document
      if (iframeDoc) {
        iframeDoc.open()
        iframeDoc.write(htmlContent)
        iframeDoc.close()

        await new Promise<void>((resolve) => {
          iframe.onload = () => {
            iframe.contentWindow?.focus()
            iframe.contentWindow?.print()
            setTimeout(() => {
              document.body.removeChild(iframe)
              resolve()
            }, 1000)
          }
        })
      }

      logger.info('PDF导出完成（web 预览打印）')
      return true
    } catch (error) {
      logger.error('导出PDF失败:', error)
      return false
    }
  }
}